package com.tbit.main.controller;


import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.*;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 故障管理
 *
 * @author Leon
 * 2019年11月16日 下午3:11:00
 */
@RestController
@RequestMapping("/machineFault")
public class MachineFaultController {
    @Autowired
    private MachineFaultService machineFaultService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private WorkOrderFinishingService workOrderFinishingService;
    @Autowired
    private RepairLogService repairLogService;
    @Autowired
    private BatteryModelService batteryModelService;
    @Autowired
    private BatteryModelDetalService batteryModelDetalService;
    @Autowired
    private MachineAttrService machineAttrService;
    @Autowired
    private BatteryService batteryService;
    @Autowired
    private MachineFaultLogService machineFaultLogService;
    @Autowired
    private GeoreMachineService georeMachineService;

    /**
     * 根据用户码查询
     */
    @RequestMapping("/getByUserCode")
    public JsonResult groupByTime(String token, String userCode, Integer mapType) {
        Assert.hasLength(userCode, "Machine.userCode.notNull");

        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }

        /**查询设备信息*/
        Machine machine = machineService.getByUseCode(userCode);
        if (machine == null) {
            throw new BaseException("Machine.notExist");
        }

        MachineFault machineFault = machineFaultService.getByMachineId(machine.getMachineId());

        /**
         * 用户故障，多次上报判断判断
         */
		/*if(machineFault.getFrom().equals(MachineFaultConstant.FAULT_USER)){
			List<MachineFault> machineUser = machineFaultService.getMachineFaultUser(machine.getAccountId(),machine.getMachineId(),null);
			if(machineUser!=null && !machineUser.isEmpty()){
				machineFault = null;
			}
		}*/

        if (machineFault != null) {
            machineFault.setMachineNO(machine.getMachineNO());
            machineFault.setUserCode(machine.getUserCode());

            /**如果有经纬度校准*/
            if (machineFault.getFrom() == 1 && machineFault.getPoint() != null && machineFault.getPoint().length() > 0) {
                String[] p = machineFault.getPoint().split(",");
                if (p.length == 2) {
                    Point point = calibrateService.commonCalibrate(new Point(Double.parseDouble(p[0]), Double.parseDouble(p[1])), mapType, MapConstant.MAP_ORI);
                    machineFault.setPointC(point.getX() + "," + point.getY());
                }
            }

            /**查询电池编号*/
            //BatteryMachine batteryMachine = batteryMachineService.getByMachineId(machine.getMachineId());
            Battery battery = batteryService.getByMachineId(machine.getMachineId());
            if (battery != null) {

                /**查询车辆绑定电池类型id*/
                MachineBatteryModel machineBatteryModel = batteryModelService.getMachineId(machine.getMachineId());

                /**查询主电池方案*/
                BatteryModel batteryModel = batteryModelService.getByModelId(machineBatteryModel.getBatteryModelId());
                machineFault.setBatteryType(batteryModel.getBatteryType());

                /**氢电池查询电量*/
                if (batteryModel.getBatteryType().equals(BatteryConstant.Battery_type_qdc)) {
                    if (machineBatteryModel.getSecondaryBattertId() != null) {

                        List<BatteryModelDetail> batteryModelDetails = batteryModelDetalService.getByModelId(machineBatteryModel.getSecondaryBattertId());

                        MachineEvent machineEvent = machineAttrService.getMachineEvent(machineFault.getMachineNO(), "tLiSOC");

                        if (batteryModelDetails != null && machineEvent != null && batteryModelDetails.size() > 0 && machineEvent.getEventValue() != null) {
                            Float vol = Float.parseFloat(machineEvent.getEventValue());
                            Boolean update = false;
                            for (BatteryModelDetail batteryModelDetail : batteryModelDetails) {
                                if (batteryModelDetail.getMinVol() <= vol && vol <= batteryModelDetail.getMaxVol()) {
                                    /**更新电量*/
                                    machineFault.setSecondaryBattery(batteryModelDetail.getBatteryPer());
                                    update = true;
                                    break;
                                }
                            }

                            /**如果电池方案没有匹配上*/
                            if (!update) {
                                /**更新电量*/
                                machineFault.setSecondaryBattery(-1);
                            }
                        }
                    }
                }
            }
        }

        return JsonResult.succ(machineFault);
    }

    /**
     * 添加或者更新
     */
    @RequestMapping("/addOrUpdate")
    public JsonResult<String> addOrUpdate(String token, MachineFault machineFault) {
        Assert.hasLength(machineFault.getUserCode(), "Machine.userCode.notNull");
        AccountUser accountUserToken = tokenService.getAccount(token);
        machineFaultService.addMachineFault(machineFault, accountUserToken);
        return JsonResult.succ();
    }

    /**
     * 恢复正常
     */
    @RequestMapping("/handle")
    public JsonResult handle(String token, String userCode) {
        Assert.hasLength(userCode, "Machine.userCode.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        /**查询设备信息*/
        Machine machine = machineService.getByUseCode(userCode);
        if (machine == null) {
            throw new BaseException("Machine.notExist");
        }

        /**删除记录*/
        MachineFault machineFault = machineFaultService.getByMachineId(machine.getMachineId());
        if (machineFault != null) {
            machineFaultService.del(machine.getMachineId());
        }

        /**更改车辆状态*/
        machineService.changeState(machine.getMachineId(), MachineStateConstant.MACHINE_STATE_ZCYY);

        /***
         * 添加故障上报日志
         */
        MachineFaultLog machineFaultLog = new MachineFaultLog();
        GeoreMachine georeMachine = georeMachineService.getByMachineId(machine.getMachineId());
        machineFaultLog.setAccountId(machine.getAccountId());
        if (georeMachine != null) {
            machineFaultLog.setRegionId(georeMachine.getRegionId());
        }
        machineFaultLog.setMachineId(machine.getMachineId());
        machineFaultLog.setUserCode(machine.getUserCode());
        machineFaultLog.setAddManId(accountUser.getAccountUserId());
        machineFaultLog.setAddTime(DateTimeUtil.getNowTime());
        machineFaultLog.setIntoMain(0);
        machineFaultLog.setMachineType(machine.getMachineType());
        machineFaultLog.setFaultType(MachineFaultLogConstant.RESTORE_TO_NORMAL);
        machineFaultLog.setAddManName(accountUser.getName());
        machineFaultLog.setAddManPhone(accountUser.getPhone());
        if (machineFault != null) {
            machineFaultLog.setFaults(machineFault.getFaults());
            if (machineFault.getOrderNO() == null) {
                machineFaultLog.setOrderNO(OrderUtil.getNO());
            } else {
                machineFaultLog.setOrderNO(machineFault.getOrderNO());
            }
        } else {
            machineFaultLog.setOrderNO(OrderUtil.getNO());
        }
        machineFaultLogService.insert(machineFaultLog);


        /**判断是否存在工单*/
		/*String redisKey = machine.getAccountId()+"_"+machine.getUserCode()+"_"+
				WorkOrderConstant.workType_WX+"_"+RedisConstant.REDIS_WORK_ORDER;
		String workOrderId = redisService.get(redisKey);

		String time = null;
		if(workOrderId!=null){
			WorkOrder workOrder = workOrderService.getByWorkOrderId(workOrderId);
			time = workOrder.getBuildTime();
		}*/

        WorkOrderFinishing workOrderFinishing = workOrderFinishingService.getByWorkMachineIdState(WorkOrderConstant.workType_WX, machine.getMachineId(), null);
        String time = null;
        if (workOrderFinishing != null) {
            WorkOrder workOrder = workOrderService.getByWorkOrderId(workOrderFinishing.getWorkOrderId());
            time = workOrder.getBuildTime();
        }

        RepairLog repairLog = repairLogService.getByFirst(machine.getMachineId(), accountUser.getAccountUserId(), time);
        Integer businessNO = null;
        Integer isValid = 0;
        if (repairLog != null) {
            businessNO = repairLog.getRepairLogId();
            isValid = 1;
        }
        /**有效维修工单*/
        workOrderService.endWork(WorkOrderConstant.workType_WX, accountUser, machine.getMachineId(), businessNO, isValid, null, WorkOrderConstant.state_WC);

        return JsonResult.succ();
    }

}